﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dataglot
{
    public class NullUtils
    {
        public static object ConvertNullToDbNull(object value)
        {
            object returnValue = value;

            if (returnValue == null)
            {
                return DBNull.Value;
            }

            //if(value.GetType()==typeof(Version))
            //if (returnValue!=null && returnValue is Version)
            //Type current = value.GetType();
            //Type versionType = typeof (Version);
            //if (current.ToString() == versionType.ToString())
            //if(Object.ReferenceEquals(value.GetType(),(new Version()).GetType()))
            if (returnValue is Type)
            {
                returnValue = returnValue.ToString();
            }

            return returnValue;
        }

        public static object NeutralizeNulls(object value, Type type)
        {
            if (value != DBNull.Value) return value;

            if (type.ToString() == "System.String")
            {
                return "";
            }
            if (type.ToString() == "System.Int32")
            {
                return 0;
            }

            if (type.ToString() == "System.Int64")
            {
                return 0;
            }
            if (type.ToString() == "System.Boolean")
            {
                return false;
            }
            if (type.ToString() == "System.DateTime")
            {
                return DateTime.MinValue;
            }
            if (!type.IsValueType)
            {
                //It's an object, return ordinary null.
                return null;
            }

            return value;
        }
    }
}
